import authAPI from '~/api/auth'

// 用户 Store - 实际应用示例
export const useUserStore = defineStore('user', {
  // 状态
  state: () => ({
    // 用户信息
    userInfo: null,
    // 登录状态
    isLoggedIn: false,
    // 加载状态
    loading: false,
  }),
  // 计算属性
  getters: {
  },
  // 方法
  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLoggedIn = !!userInfo
      // 只在客户端保存到 localStorage
      if (process.client && userInfo) {
        localStorage.setItem('user', JSON.stringify(userInfo))
      } else if (process.client) {
        localStorage.removeItem('user')
      }
    },
    restoreUserData() {
      if (process.client) {
        try {
          const savedUser = localStorage.getItem('user')
          const savedToken = localStorage.getItem('token')
          if (savedUser && savedToken) {
            const userInfo = JSON.parse(savedUser)
            this.userInfo = userInfo
            this.isLoggedIn = true
            return true
          }
        } catch (error) {
          localStorage.removeItem('user')
          localStorage.removeItem('token')
        }
      }
      return false
    },
    async getUserInfo() {
      this.loading = true
      try {
        const response = await authAPI.getUserInfo()
        if (response.code === 200) {
          this.setUserInfo(response.data.user)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      } finally {
        this.loading = false
      }
    },
  }
}) 